// 请求基地址
import type {Result} from "@/types/Result";
import {useUserStore} from "@/stores/user";

let baseURL: string
//条件编译
// #ifdef H5
baseURL = '/api'
// #endif

// #ifndef H5
baseURL = 'http://120.48.126.162:8080'
// #endif

/**
 *  解决微信小程序端session不一致
 */

// 拦截器配置
const httpInterceptor = {
    // 拦截前触发
    invoke(options: UniApp.RequestOptions) {
        // 1. 非 http 开头需拼接地址
        if (!options.url.startsWith('http')) {
            options.url = baseURL + options.url
        }
        // 2. 请求超时
        options.timeout = 15000
        // 3. 添加小程序端请求头标识
        options.header = {
            ...options.header,
            'Access-Control-Allow-Origin': '*'
        }
        // 4. 添加 token 请求头标识
        const userStore = useUserStore()
        const token = userStore.userInfoData?.token
        if (token) {
            options.header.token = token
        }
    },
}
uni.addInterceptor('request', httpInterceptor)
// 拦截 uploadFile 文件上传
uni.addInterceptor('uploadFile', httpInterceptor)

// 请求promise化
export const request = <T>(options: UniApp.RequestOptions) => {
    return new Promise<Result<T>>((resolve, reject) => {
        if (options.method !== 'PUT' && options.url !== '/AW/guessLike' && options.url !== '/suggest') {
            //uni.showLoading({ title: '加载中...' })
        }
        uni.request({
            ...options,
            success: (res: any) => {
                uni.hideLoading()
                if (options.url.split('?')[0] === '/user/login') {
                    resolve(res.data as Result<T>)
                }
                // 这里的success只要服务器有响应便会执行，因此需要再判断一下
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    if (res.data.code?.toString() !== '1') {
                        uni.showToast({
                            title: (res.data as Result<T>).message || '服务器繁忙！请稍后重试',
                            icon: 'none',
                        })
                        reject(res)
                    }
                    resolve(res.data as Result<T>)
                } else if (res.statusCode === 401) {
                    uni.showToast({
                        title: '登录过期，请重新登录',
                        icon: 'none',
                    })
                    const userStore = useUserStore()
                    userStore.clearUserInfo()
                    uni.navigateTo({url: '/subPkg/login/login'})
                    reject(res)
                }  else {
                    uni.showToast({
                        title: (res.data as Result<T>).message || '服务器繁忙！请稍后重试',
                        icon: 'none',
                    })
                }
            },
            fail: (err) => {
                uni.hideLoading()
                uni.showToast({
                    title: '系统繁忙！请稍后重试',
                    icon: 'none',
                    duration: 2000,
                })
                const network = plus.networkinfo.getCurrentType()
                if (network === plus.networkinfo.CONNECTION_NONE) {
                    uni.$emit("noNetwork")
                }
                reject(err)
            },
        })
    })
}
